package cn.com.zero.base.config;

import cn.com.zero.base.util.RedisUtil;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author xiongxj
 * @version 1.0.0
 * @Description Redis配置
 * @createTime 2023/2/28 15:14
 */
@Configuration
@ConditionalOnProperty(name = "spring.redis.enabled", havingValue = "true")
@AutoConfigureBefore(value = {RedisAutoConfiguration.class})
public class RedisConfig {

    @Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

        /**
         * 查看redis的配置加载，入口为：spring-boot-autoconfigure 包
         * org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration
         */

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // 设置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 序列化器的比较，可参考：https://blog.csdn.net/F_Hello_World/article/details/103724193
        // 设置key的序列化器，默认是使用的 JdkSerializationRedisSerializer
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        // 设置value的序列化器，此处采用默认的 JdkSerializationRedisSerializer
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    /**
     * 实例化
     *
     * @param redisTemplate redisTemplate
     * @return redis工具类
     */
    @Bean(name = "redisUtil")
    @ConditionalOnSingleCandidate(RedisTemplate.class)
    @SuppressWarnings("unchecked")
    public RedisUtil<Object> redisUtil(RedisTemplate redisTemplate) {
        RedisUtil<Object> redisUtil = new RedisUtil<>();
        redisUtil.setRedisTemplate(redisTemplate);
        return redisUtil;
    }
}
